<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" size="mini">
      <el-row :gutter="15">
        <div class="orderNo">采购单号：{{ form.procureNo }}</div>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="4">
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="form.supplierId" filterable placeholder="请选择供应商">
              <el-option v-for="item in supplierOptions" :key="item.supplierId" :label="item.supplierName" :value="item.supplierId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="采购日期" prop="procureTime">
            <el-date-picker v-model="form.procureTime" clearable placeholder="请选择采购日期" type="date" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="采购人" prop="procurePersonId">
            <el-select v-model="form.procurePersonId" filterable placeholder="请选择采购人" @change="handleSelectedUser">
              <el-option v-for="item in personOptions" :key="item.userId" :label="item.nickName" :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="联系电话">
            <el-input v-model="form.procurePersonPhone" :disabled="true" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button :disabled="!form.supplierId" icon="el-icon-plus" plain size="mini" type="primary" @click="handleAddCommodity">添加商品</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="form.detailsList" :summary-method="getSummaries" show-summary border>
        <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
        <el-table-column align="center" label="商品编号" prop="supplierCommodityNo"/>
        <el-table-column align="center" label="商品名称" prop="supplierCommodityName"/>
        <el-table-column align="center" label="商品类别" prop="supplierCommodityType"/>
        <el-table-column align="center" label="规格" prop="supplierCommoditySpec" width="80"/>
        <el-table-column align="center" label="单位" prop="supplierCommodityUnit" width="80"/>
        <el-table-column align="center" label="采购数量" prop="procureNumber" width="120">
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.procureNumber" @input="calculateSubTotal(scope.row.procureNumber, scope.row, 'procureNumber')"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="采购单价" prop="procurePrice" width="120">
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.procurePrice" @input="calculateSubTotal(scope.row.procurePrice, scope.row, 'procurePrice')"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="小计" prop="subtotal">
          <template slot-scope="scope">
            {{ formattedNumber(calculateSubTotal(scope.row.subtotal, scope.row)) }}
          </template>
        </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template slot-scope="scope">
            <el-button icon="el-icon-delete" size="mini" type="text" @click="handleDeleteCommodity(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 合计 -->

      <el-row :gutter="15" style="margin-top: 40px">
        <el-col :span="6">
          <el-form-item label="物流费用" prop="logisticsCost">
            <el-input v-model="form.logisticsCost" class="input-with-select" placeholder="请输入" type="number">
              <el-select slot="prepend" v-model="form.logisticsMethod" placeholder="请选择" style="width: 110px;">
                <el-option v-for="item in methodOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="其他费用" prop="otherCost">
            <el-input v-model="form.otherCost" class="input-with-select" placeholder="请输入" type="number">
              <el-select slot="prepend" v-model="form.otherMethod" placeholder="请选择" style="width: 110px;">
                <el-option v-for="item in methodOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <div class="pay-amount-div">应付费用：<span class="">{{ formattedNumber(form.payAmount) }}</span></div>
      <el-row>
        <el-col :span="24">
          <el-form-item label="单据备注" prop="remark">
            <el-input v-model="form.remark" :rows="4" placeholder="请输入单据备注" type="textarea"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="附件" prop="attr">
            <file-upload v-model="form.attr" @input="handleFileInput"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer-options">
      <el-button type="primary" @click="submitForm(1)">提交审核</el-button>
      <el-button type="primary" @click="submitForm(0)">保存草稿</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!-- 选择商品 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="isCommodityOpen" append-to-body title="选择商品" width="80%">
      <ErpSupplierCommodity v-if="isCommodityOpen" :notSupplierCommodityIds="notSupplierCommodityIds" :supplierId="form.supplierId" @SelectionChange="handleSelectionChange"></ErpSupplierCommodity>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectedCommdity">确 定</el-button>
        <el-button @click="isCommodityOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getList} from "@/api/erp/ErpSupplier";
import {getSysUserList} from "@/api/system/user";
import {addErpProcure, getErpProcure, updateErpProcure,} from "@/api/erp/ErpProcure";
import ErpSupplierCommodity from "@/views/erp/ErpSupplier/selectedSupplierCommodity";
import {formattedNumber} from "@/utils/ruoyi";

export default {
  components: {
    ErpSupplierCommodity,
  },
  props: [],
  dicts: ["erp_procure_batch", "erp_logistics_stauts"],
  data() {
    return {
      // 分摊方式
      methodOptions: [
        {
          value: 1,
          label: "按重量分摊",
        },
        {
          value: 2,
          label: "按体积分摊",
        },
      ],
      // 采购人列表
      personOptions: [],
      // 商品table loading
      loading: true,
      // 供应商列表
      supplierOptions: [],
      // 临时存放
      temporyList: [],
      // 选择商品弹框
      isCommodityOpen: false,
      form: {},
      rules: {
        supplierId: [
          {required: true, message: "请选择供应商", trigger: "blur"},
        ],
        procureTime: [
          {required: true, message: "采购日期不能为空", trigger: "blur"},
        ],
        procurePersonId: [
          {required: true, message: "采购人不能为空", trigger: "blur"},
        ],
      },
      // 商品过滤id
      notSupplierCommodityIds: []
    };
  },
  computed: {
    calculateSubtotal() {
      let subtotalSum = 0;
      this.form.detailsList.forEach((item) => {
        subtotalSum += item.subtotal;
      });
      return (
        parseFloat(!this.form.logisticsCost ? 0 : this.form.logisticsCost) +
        parseFloat(!this.form.otherCost ? 0 : this.form.otherCost) +
        subtotalSum
      );
    },
  },
  watch: {
    "form.detailsList.subtotal": {
      handler(newVal) {
        this.form.payAmount = this.calculateSubtotal;
      },
      deep: true,
    },
  },
  created() {
    this.reset();
    this.handleGetListErpSupplier();
    this.handleGetListSysUser();
    this.getList();
    const procureId = this.$route.params && this.$route.params.procureId;
    if (procureId != 0) {
      this.getProcureInfo(procureId);
    }
  },
  mounted() {
  },
  methods: {
    formattedNumber,
    // 根据供应商id查询该供应商下商品
    getList() {
      this.loading = false;
    },
    // 获取供应商列表
    handleGetListErpSupplier() {
      getList().then((res) => {
        this.supplierOptions = res.data;
      });
    },
    // 获取用户列表
    handleGetListSysUser() {
      getSysUserList().then((res) => {
        this.personOptions = res.data;
      });
    },
    getProcureInfo(procureId) {
      getErpProcure(procureId).then((response) => {
        this.form = response.data;
      });
    },
    // 采购人选择回调
    handleSelectedUser(e) {
      let obj = this.personOptions.find(i => {
        return i.userId == e
      })
      this.form.procurePersonPhone = obj.phonenumber;
    },
    // 表单重置
    reset() {
      this.form = {
        procureNo: "CG" + this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}'),
        supplierId: null,
        procureTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
        procurePersonId: null,
        logisticsCost: null,
        logisticsMethod: 1,
        otherCost: null,
        otherMethod: 1,
        payAmount: null,
        logisticsStauts: 0,
        remark: null,
        attr: null,
        createId: null,
        createName: null,
        createTime: null,
        flag: null,
        approveStatus: null,
        approveId: null,
        approveName: null,
        approveTime: null,
        rejectTime: null,
        rejectReason: null,
        procureStatus: null,
        procureBatch: 0,
        detailsList: [],
      };
      this.resetForm("form");
    },
    // 选择商品
    handleAddCommodity() {
      this.notSupplierCommodityIds = this.form.detailsList.map(item => item.commodityId);
      this.isCommodityOpen = true;
    },
    // 提交数据
    submitForm(type) {
      if(this.form.detailsList.length == 0){
        return this.$message.error('请选择采购商品！');;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.procureStatus = type;
          if (this.form.procureId != null) {
            updateErpProcure(this.form).then((response) => {
              this.$modal.msgSuccess("操作成功");
              const obj = {path: "/psi/purchase/ErpProcure", name: "ErpProcure"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          } else {
            addErpProcure(this.form).then((response) => {
              this.$modal.msgSuccess("操作成功");
              const obj = {path: "/psi/purchase/ErpProcure", name: "ErpProcure"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          }
        }
      });
    },
    // 取消
    cancel() {
      const obj = {path: "/psi/purchase/ErpProcure", name: "ErpProcure"};
      this.$tab.closeOpenPage(obj);
      this.$tab.refreshPage(obj);
    },
    // 商品选择
    handleSelectionChange(selection) {
      this.temporyList = selection;
    },
    // 确定选择商品
    submitSelectedCommdity() {
      this.temporyList.forEach((item) => {
        this.form.detailsList.push({
          ...item,
          procurePrice: item.supplierCommodityQuotation,
          supplierCommodityType: item.commodityTypeName,
          commodityId: item.supplierCommodityId,
        });
      });
      this.isCommodityOpen = false;
    },
    /** 删除商品 */
    handleDeleteCommodity(row) {
      const index = this.form.detailsList.indexOf(row);
      if (index > -1) {
        this.form.detailsList.splice(index, 1);
      }
      this.notSupplierCommodityIds = this.notSupplierCommodityIds.filter(function (item) {
        return item !== row.commodityId;
      });
    },
    // 附件上传成功
    handleFileInput(e) {
      this.form.attr = e;
    },
    /** 计算小计 */
    calculateSubTotal(v, row, field) {
      if (v) {
        row[field] = v;
      }
      row.subtotal =
        parseFloat(!row.procurePrice ? 0 : row.procurePrice) *
        parseFloat(!row.procureNumber ? 0 : row.procureNumber);
      this.form.payAmount = 0;
      let subtotalSum = 0;
      this.form.detailsList.forEach((item) => {
        subtotalSum += item.subtotal;
      });
      this.form.payAmount =
        parseFloat(!this.form.logisticsCost ? 0 : this.form.logisticsCost) +
        parseFloat(!this.form.otherCost ? 0 : this.form.otherCost) +
        subtotalSum;
      return row.subtotal;
    },
    /** 自定义合计 */
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (
          ["supplierCommodityUnit","procureNumber", "procurePrice", "subtotal"].includes(
            column.property
          )
        ) {
          if (index === 5) {
            sums[index] = "合计：";
          } else {
            const values = data.map((item) => Number(item[column.property]));
            if (!values.every((value) => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  let v = prev + curr;
                  return parseFloat(v.toFixed(4));
                } else {
                  return prev;
                }
              }, 0);
            } else {
              sums[index] = "0";
            }
          }
        }
      });
      return sums;
    },
  },
};
</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
